//
// CheckTpm.c : Get TPM device information, such as TPM 1.2 or 2.0.
// Refer to https://docs.microsoft.com/en-us/windows/win32/api/tbs/nf-tbs-tbsi_getdeviceinfo
// Compiled in VS2013/2019.
//

#include <windows.h>
#include <stdio.h>
#include <Tbs.h>
#pragma comment(lib, "Tbs.lib")

int main()
{
	TBS_RESULT      TbsResult;
	TPM_DEVICE_INFO TpmDeviceInfo = { 0 };
	UINT32          TpmDeviceInfoSize = sizeof(TPM_DEVICE_INFO);
	const char*     TpmDeviceType0 = "Unknow interface";
	const char*     TpmDeviceType1 = "I/O-port or MMIO";
	const char*     TpmDeviceType2 = "TrustZone";
	const char*     TpmDeviceType3 = "Hardware";
	const char*     TpmDeviceType4 = "Emulator";
	const char*     TpmDeviceType5 = "SPB";

	const char*     TpmDeviceTypeString[] = {
		                                      TpmDeviceType0,
		                                      TpmDeviceType1,
		                                      TpmDeviceType2,
		                                      TpmDeviceType3,
		                                      TpmDeviceType4,
		                                      TpmDeviceType5
	                                         };

	TbsResult = Tbsi_GetDeviceInfo(TpmDeviceInfoSize, (PVOID)& TpmDeviceInfo);

	if (TBS_E_TPM_NOT_FOUND == TbsResult) {
		printf("TPM device is not found.");
		return 1;
	} else if (TBS_SUCCESS != TbsResult) {
		printf("Unknown error!");
		return 2;
	}

	if (TpmDeviceInfo.tpmInterfaceType >= sizeof(TpmDeviceTypeString) / sizeof(TpmDeviceTypeString[0])) {
		return -1;
	}
	printf("%s ", TpmDeviceTypeString[TpmDeviceInfo.tpmInterfaceType]);

	if (TPM_VERSION_12 == TpmDeviceInfo.tpmVersion) {
		printf("TPM 1.2");
	} else if (TPM_VERSION_20 == TpmDeviceInfo.tpmVersion) {
		printf("TPM 2.0");
	} else {
		printf("Unknow TPM version! %d", TpmDeviceInfo.tpmVersion);
	}

	return 0;
}